package com.copro.chemdb.stat.rule;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.util.Properties;

import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.stat.StatRule;
import com.copro.chemdb.subject.Subject;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;
import com.copro.simple.db.QueryCallback;
import com.copro.simple.db.QuickQueryCallback;

public class Rule6 implements StatRule {

	private String comCode;
	private String dbCode;
	private String startCode;
	private String endCode;
	private String dueCode;

	@Override
	public StatResult doStat(Application app, Subject subject, int type)
			throws SimpleException {
		SQLSegment sql = app.getSQL("rule6List");
		sql.set("comCode", comCode);
		sql.set("dbCode", dbCode);
		sql.set("startCode", startCode);
		sql.set("endCode", endCode);
		sql.set("dueCode", dueCode);
		sql.set("type", type);
		List<List<String>> rows = new LinkedList<List<String>>();
		QueryCallback callback = new QuickQueryCallback(rows) {
			@SuppressWarnings("unchecked")
			@Override
			public void exec(ResultSet rs) throws SQLException {
				while (rs.next()) {
					List<String> list = new ArrayList<String>(5);
					list.add(rs.getString("cName"));
					list.add(rs.getString("dbName"));
					list.add(rs.getString("start"));
					list.add(rs.getString("finish"));
					list.add(rs.getString("dur"));
					((List) obj).add(list);
				}
			}
		};
		app.query(sql.toString(), callback);
		Hashtable<String, Object> result = new Hashtable<String, Object>();

		sql = app.getSQL("rule6Count");
		sql.set("dbCode", dbCode);
		sql.set("type", type);
		int len = app.getCount(sql.toString());

		result.put("count", len);
		result.put("rows", rows);
		result.put("text", subject.getBrief());
		return new StatResult("rule6", result);
	}

	@Override
	public void setup(Properties conf) {
		comCode = conf.getStringTrimed("comCode");
		dbCode = conf.getStringTrimed("dbCode");
		startCode = conf.getStringTrimed("startCode");
		endCode = conf.getStringTrimed("endCode");
		dueCode = conf.getStringTrimed("dueCode");
	}

}
